﻿using UnityEngine;
using System.Collections;

public class Zinimigo : MonoBehaviour 
{
	public Transform Player;
	public Transform Enemy;
	int dropinimigo = 0;
	//new Vector3 movi(transform.position.x +1, transform.position.y, transform.position.z);
	
	// Update is called once per frame
	void Update ()
	{
	if(dropinimigo > 0)
	{
			Debug.Log("TESTAAEE");
			Instantiate(Enemy, transform.position, transform.rotation);
			dropinimigo--;
	}

		distanceControl();

	}

	void  OnTriggerEnter (Collider col)
	{
		if(col.gameObject.tag == "Finish")
		{
			dropinimigo = 0;
			Debug.Log(dropinimigo);
			Destroy(gameObject);
			Instantiate(Enemy, new Vector3(transform.position.x-10, transform.position.y,transform.position.z), transform.rotation);
			Instantiate(Enemy, new Vector3(transform.position.x-13, transform.position.y,transform.position.z) , transform.rotation );
			Instantiate(Enemy, new Vector3(transform.position.x-15, transform.position.y,transform.position.z) , transform.rotation );
			//dropinimigo = 0;
		}
	}
		
	void distanceControl()
	{
		float distanceToPlayer = Vector3.Distance(transform.position, Player.position);
		if(distanceToPlayer < 1000 && distanceToPlayer > 2)
		{
			followPlayer(true);
		}
		
		else
		{			
			followPlayer(false);
			
		}
	
	}

	void followPlayer(bool enabled)
	{
		if(enabled)
		{		
			Vector3 Direcao = (Player.position - transform.position).normalized;
			transform.position += Direcao * Time.deltaTime * 5;
			Quaternion newRotation = Quaternion.LookRotation(Direcao);
			transform.rotation = newRotation;
		}
		
		else
		{
			return;
	
		}	
	}
}
